<?php
declare (strict_types = 1);
namespace app\adminapi\logic\system\auth;
use adminmatrix\server\app\logic\BaseLogic;
use adminmatrix\annotation\Inject;
use app\adminapi\model\system\auth\AdminRolePermission;
use app\adminapi\model\system\auth\AdminUser;
use app\adminapi\model\system\auth\AdminUserRole;
use app\adminapi\model\system\auth\Permission as PermissionModel;
use app\adminapi\validate\system\auth\PermissionValidate;
use app\Request;

class PermissionLogic extends BaseLogic
{
    #[Inject]
    protected PermissionModel $model;


    public function tree(Request $request): \think\Collection|array
    {
        return buildTreeWithRemove($this->model->whereNotIn('type',[3])->select() -> toArray());
    }

    public function treeAll(Request $request) : mixed
    {
        return buildTreeWithRemove($this->model->select() -> toArray());
    }


    public static function getAllAuth(){
        return (new PermissionModel) -> distinct(true)->where('perms',"<>",'')->column('perms');
    }


    public static function getAuthByAdminId(int $adminId) : array
    {
        $roleIds = AdminUserRole::where('user_id' , $adminId) ->column('role_id');
        $menuId  = AdminRolePermission::whereIn('role_id' , $roleIds)->column('permission_id');

        return PermissionModel::where([
            ["perms" , "<>" , ""]
        ])->column('perms');
    }

    public static function getMenuByAdminId($adminId) : array
    {
        $admin = (new AdminUser) -> findOrEmpty($adminId);
        $where = [];
        $menu = new PermissionModel;
        $where[] = ['type' ,'in' , [1,2]];
        if ($admin->root != 1)
        {
            $roleMenu = AdminRolePermission::whereIn('role_id' , $admin->role->column('role_id'))->column('permission_id');
           $where[] = ['id' , 'in' , $roleMenu];
        }
        return buildTree($menu->where($where)->fetchSql(false)->select()->toArray());
    }

}